'use client';

import { useState, useEffect } from 'react';
import { Box, Container, Typography, Card, CardContent, Button, Alert, Snackbar, CircularProgress, Grid, Tabs, Tab, Paper } from '@mui/material';
import { useRouter } from 'next/navigation';
import ArticleIcon from '@mui/icons-material/Article';
import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';
import BookIcon from '@mui/icons-material/Book';
import { getQuestions } from '@/api/questions';

interface LearningMaterial {
  id: number;
  title: string;
  type: 'document' | 'video' | 'article';
  description: string;
  subject: string;
  url: string;
  createdAt: string;
}

interface Question {
  id: number;
  type: string;
  content: string;
  options: string[];
  answer: string;
  explanation: string;
  subject: string;
  score: number;
}

// 模拟学习资料数据
const mockMaterials: LearningMaterial[] = [
  {
    id: 1,
    title: '高中数学必修一知识点总结',
    type: 'document',
    description: '全面覆盖高中数学必修一的重要知识点，包含详细解析和例题',
    subject: '数学',
    url: '#',
    createdAt: '2024-01-15'
  },
  {
    id: 2,
    title: '物理实验操作视频教程',
    type: 'video',
    description: '详细讲解高中物理各类实验的标准操作流程',
    subject: '物理',
    url: '#',
    createdAt: '2024-01-16'
  },
  {
    id: 3,
    title: '英语语法专项训练',
    type: 'article',
    description: '系统性的英语语法知识讲解和练习题',
    subject: '英语',
    url: '#',
    createdAt: '2024-01-17'
  }
];

export default function LearningPage() {
  const [materials, setMaterials] = useState<LearningMaterial[]>([]);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(true);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const [currentTab, setCurrentTab] = useState(0);
  const [selectedSubject, setSelectedSubject] = useState<string>('全部');
  const router = useRouter();

  useEffect(() => {
    // 检查用户是否登录
    const user = localStorage.getItem('user');
    console.log(user)
    if (!user) {
      router.push('/login');
      return;
    }

    // 加载学习资料和题目
    const fetchData = async () => {
      try {
        setMaterials(mockMaterials);
        const questionsData = await getQuestions();
        setQuestions(questionsData);
      } catch (error) {
        setSnackbar({
          open: true,
          message: '获取数据失败',
          severity: 'error'
        });
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [router]);

  const getIcon = (type: string) => {
    switch (type) {
      case 'document':
        return <ArticleIcon sx={{ fontSize: 40 }} />;
      case 'video':
        return <VideoLibraryIcon sx={{ fontSize: 40 }} />;
      case 'article':
        return <BookIcon sx={{ fontSize: 40 }} />;
      default:
        return <ArticleIcon sx={{ fontSize: 40 }} />;
    }
  };

  const handleMaterialClick = (material: LearningMaterial) => {
    // 暂时只显示提示信息，后续实现实际的查看功能
    setSnackbar({
      open: true,
      message: '该功能正在开发中',
      severity: 'info'
    });
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <CircularProgress size={60} />
      </div>
    );
  }

  // 获取所有科目
  const subjects = ['全部', ...Array.from(new Set(questions.map(q => q.subject)))];

  // 根据选中的科目筛选题目
  const filteredQuestions = selectedSubject === '全部' 
    ? questions 
    : questions.filter(q => q.subject === selectedSubject);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  const handleSubjectChange = (subject: string) => {
    setSelectedSubject(subject);
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        在线学习
      </Typography>

      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
        <Tabs value={currentTab} onChange={handleTabChange}>
          <Tab label="学习资料" />
          <Tab label="题目学习" />
        </Tabs>
      </Box>

      {currentTab === 0 ? (
        <Grid container spacing={3}>
          {materials.map((material) => (
          <Grid item xs={12} sm={6} md={4} key={material.id}>
            <Card 
              sx={{ 
                height: '100%', 
                display: 'flex', 
                flexDirection: 'column',
                '&:hover': {
                  boxShadow: 6,
                  cursor: 'pointer'
                }
              }}
              onClick={() => handleMaterialClick(material)}
            >
              <CardContent sx={{ flexGrow: 1 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                  {getIcon(material.type)}
                  <Typography variant="h6" component="div" sx={{ ml: 1 }}>
                    {material.title}
                  </Typography>
                </Box>
                <Typography variant="body2" color="text.secondary" paragraph>
                  {material.description}
                </Typography>
                <Typography variant="body2" color="primary">
                  科目：{material.subject}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  上传时间：{material.createdAt}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        ))}
        </Grid>
      ) : (
        <>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              按科目筛选：
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {subjects.map((subject) => (
                <Button
                  key={subject}
                  variant={selectedSubject === subject ? 'contained' : 'outlined'}
                  onClick={() => handleSubjectChange(subject)}
                  sx={{ mb: 1 }}
                >
                  {subject}
                </Button>
              ))}
            </Box>
          </Box>

          <Grid container spacing={3}>
            {filteredQuestions.map((question) => (
              <Grid item xs={12} key={question.id}>
                <Paper sx={{ p: 3 }}>
                  <Typography variant="h6" gutterBottom>
                    {question.content}
                  </Typography>
                  {question.type === 'CHOICE' && (
                    <Box sx={{ ml: 2 }}>
                      {(() => {
                        let options = [];
                        if (Array.isArray(question.options)) {
                          options = question.options;
                        } else if (typeof question.options === 'string') {
                          try {
                            options = JSON.parse(question.options);
                            if (!Array.isArray(options)) {
                              options = question.options.split(',').filter(Boolean);
                            }
                          } catch {
                            options = question.options.split(',').filter(Boolean);
                          }
                        }
                        return options.map((option, index) => (
                          <Typography key={index} variant="body1">
                            {String.fromCharCode(65 + index)}. {option}
                          </Typography>
                        ));
                      })()} 
                    </Box>
                  )}
                  <Box sx={{ mt: 2, p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
                    <Typography variant="subtitle1" color="primary" gutterBottom>
                      答案：{question.type === 'CHOICE' 
                        ? `${question.answer}` 
                        : question.answer}
                    </Typography>
                    <Typography variant="body1">
                      解析：{question.explanation}
                    </Typography>
                  </Box>
                  <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                    科目：{question.subject} | 题型：{question.type === 'CHOICE' ? '选择题' : 
                                                question.type === 'TRUE_FALSE' ? '判断题' : 
                                                question.type === 'FILL_BLANK' ? '填空题' : '简答题'}
                  </Typography>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
}